/*
 * bsp_uart.c
 *
 *  Created on: Mar 3, 2024
 *      Author:SDJX
 */

#include "bsp_uart.h"
#include "bsp.h"
#include "string.h"
#include "stdbool.h"
#include "imu.h"

uint8_t RxBuffer[64]={0};
bool RxSucceeflag=0;
float aX,aY,aZ,RollX,PitchY,YawZ,wX,wY,wZ;

#define ENABLE_UART_DMA    1

uint8_t RxTemp = 0;
uint8_t RxTemp_2 = 0;
static uint8_t uart4_RxTemp = 0;

// Initialize USART1  初始化串口1
void USART1_Init(void)
{
	//HAL_UART_Receive_IT(&huart1, (uint8_t *)RxBuffer, 44);
    //HAL_UART_Receive_IT(&huart1, (uint8_t *)&RxTemp, 1);
    //HAL_UART_Receive_IT(&huart2, (uint8_t *)&RxTemp_2,1);
    HAL_UART_Receive_IT(&huart4, (uint8_t *)&uart4_RxTemp,1);
}

// The serial port sends one byte  串口发送一个字节
void USART1_Send_U8(uint8_t ch)
{
    HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
}

void UART4_Send_U8(uint8_t ch)
{
    HAL_UART_Transmit(&huart4, (uint8_t *)&ch, 1, 0xFFFF);
}

void uart4_send_bytes(uint8_t* byte, uint8_t len)
{
	for(uint8_t i = 0; i < len ;i++)
	{
		UART4_Send_U8(byte[i]);
	}
}

// The serial port sends a string of data  串口发送一串数据
void USART1_Send_ArrayU8(uint8_t *BufferPtr, uint16_t Length)
{
    #if ENABLE_UART_DMA
    HAL_UART_Transmit_DMA(&huart1, BufferPtr, Length);
    #else
    while (Length--)
    {
        USART1_Send_U8(*BufferPtr);
        BufferPtr++;
    }
    #endif
}

char checkSum(unsigned char *p){//校验
	unsigned char cs=0,ii=0;
	cs=ii=0;
	while(ii<=12){
		cs+=*p++;
		ii++;
		if(ii>=11){
			if(*p==cs)return 1;
			else return 0;
		}
	}
	return -1;
}


// The serial port receiving is interrupted. Procedure  串口接收完成中断
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	UNUSED(huart);
	if(huart->Instance  == UART4)
	{
		HAL_UART_Receive_IT(&huart4, (uint8_t*) &uart4_RxTemp, 1);
		ring_buf_put(&imu.imu_rb, &uart4_RxTemp, 1); /* 将收到的陀螺仪数据放到队列中 */
	}
}


#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
PUTCHAR_PROTOTYPE
{
    /* Place your implementation of fputc here */
    /* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
    HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
    return ch;
}
